import multiprocessing

import numpy
import requests
import ConnectMySql

conn, cursor = ConnectMySql.openConn()


def getMusicLyrics(musicRid):
    url = f"http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId={musicRid}"
    response = requests.get(url)

    try:
        res = response.json()
        if res['status'] == 200 and res['data']['lrclist'] is not None:
            lrclist_ = res['data']['lrclist']
            if len(lrclist_) > 0:
                for lrc in lrclist_:
                    cursor.execute("insert into lyrics VALUES (0,%s,%s,%s)",
                                   (float(lrc['time']), lrc['lineLyric'], musicRid))
                    conn.commit()
    except Exception as e:
        print(e)
        pass


if __name__ == '__main__':
    pool = multiprocessing.Pool()

    cursor.execute("select musicRid from music")
    musicArray = cursor.fetchall()
    musicArray = numpy.array(musicArray)

    for music in musicArray:
        pool.apply_async(getMusicLyrics, args=(music[0],))

    pool.close()
    pool.join()

    ConnectMySql.closeConn(conn, cursor)
